package com.nongcai159.mall.lib_common.utils.imageloader

import android.content.ComponentCallbacks2
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import com.nongcai159.mall.lib_common.base.BaseApplication
import com.nongcai159.mall.lib_common.utils.ScreenSupport
import com.nongcai159.mall.lib_common.utils.imageloader.ImageLoader.Transformation.*
import jp.wasabeef.glide.transformations.BlurTransformation
import jp.wasabeef.glide.transformations.MaskTransformation
import jp.wasabeef.glide.transformations.RoundedCornersTransformation

/**
 * Created by tanbiheng on 2018/11/23.
 */

object ImageLoader {

    enum class Transformation {
        CIRCLE, ROUND, BLUR, MASK
    }


    /**
     * 加载图片(兼容gif)
     *
     * @param context
     * @param imageView
     * @param resouse       类型为url file resId byte[] uri
     * @param placeholder   加载占位图 默认为颜色为#FFF2F2F2的图片
     * @param error         错误占位图 默认为颜色为#FFF2F2F2的图片
     * @param strategy      缓存策略 默认为自动选择
     * @param anim          是否使用淡入淡出动画 true动画 false没有动画
     */
    fun loadImage(context: Context,
                  imageView: ImageView,
                  resouse: Any,
                  placeholder: Any = ColorDrawable(Color.parseColor("#FFF2F2")),
                  error: Any = ColorDrawable(Color.parseColor("#FFF2F2")),
                  strategy: DiskCacheStrategy = DiskCacheStrategy.AUTOMATIC,
                  anim: Boolean = true) {
        val options = RequestOptions()
        options.run {
            diskCacheStrategy(strategy)

            when (placeholder) {
                is Int -> placeholder(placeholder)
                is Drawable -> placeholder(placeholder)
                else -> placeholder(ColorDrawable(Color.parseColor("#FFF2F2")))
            }

            when (error) {
                is Int -> error(error)
                is Drawable -> error(error)
                else -> error(ColorDrawable(Color.parseColor("#FFF2F2")))
            }

            if (anim) {
                withCrossFade()
            }
        }

        Glide.with(context).load(resouse)
                .apply(options).into(imageView)
    }

    /**
     * 加载转换图片
     *
     * @param context
     * @param imageView
     * @param resouse       类型为url file resId byte[] uri
     * @param transForm     裁剪类型 默认圆角裁剪
     * @param cornerType    圆角裁剪圆角类型 默认全部圆角
     * @param radius        圆角裁剪弧度 默认5dp
     * @param maskResId     蒙版裁剪资源图片
     * @param placeholder   加载占位图 默认为颜色为#FFF2F2F2的图片
     * @param error         错误占位图 默认为颜色为#FFF2F2F2的图片
     * @param strategy      缓存策略 默认为自动选择
     * @param anim          是否使用淡入淡出动画 true动画 false没有动画
     */
    fun loadTransformImage(context: Context,
                           imageView: ImageView,
                           resouse: Any,
                           transForm: Transformation = CIRCLE,
                           cornerType: RoundedCornersTransformation.CornerType = RoundedCornersTransformation.CornerType.ALL,
                           radius: Int = ScreenSupport.dp2px(5F),
                           maskResId: Int = 0,
                           placeholder: Any = ColorDrawable(Color.parseColor("#FFF2F2")),
                           error: Any = ColorDrawable(Color.parseColor("#FFF2F2")),
                           strategy: DiskCacheStrategy = DiskCacheStrategy.AUTOMATIC,
                           anim: Boolean = true) {
        val options = RequestOptions()
        options.run {
            diskCacheStrategy(strategy)

            when (transForm) {
                CIRCLE -> {
                    circleCrop()
                }
                ROUND -> {
                    transforms(CenterCrop(), RoundedCornersTransformation(radius, 0, cornerType))
                }
                BLUR -> {
                    transform(BlurTransformation(25, 1))
                }
                MASK -> {
                    transform(MaskTransformation(maskResId))
                }
            }

            when (placeholder) {
                is Int -> placeholder(placeholder)
                is Drawable -> placeholder(placeholder)
                else -> placeholder(ColorDrawable(Color.parseColor("#FFF2F2")))
            }

            when (error) {
                is Int -> error(error)
                is Drawable -> error(error)
                else -> error(ColorDrawable(Color.parseColor("#FFF2F2")))
            }

            if (anim) {
                withCrossFade()
            }
        }

        Glide.with(context).load(resouse)
                .apply(options).into(imageView)
    }

    /**
     * 加载指定宽高图片
     *
     * @param context
     * @param imageView
     * @param resouse       类型为url file resId byte[] uri
     * @param width         宽
     * @param height        高
     * @param placeholder   加载占位图 默认为颜色为#FFF2F2F2的图片
     * @param error         错误占位图 默认为颜色为#FFF2F2F2的图片
     * @param strategy      缓存策略 默认为自动选择
     * @param anim          是否使用淡入淡出动画 true动画 false没有动画
     */
    fun loadResizeImage(context: Context,
                        imageView: ImageView,
                        resouse: Any,
                        width: Int,
                        height: Int,
                        placeholder: Any = ColorDrawable(Color.parseColor("#FFF2F2")),
                        error: Any = ColorDrawable(Color.parseColor("#FFF2F2")),
                        strategy: DiskCacheStrategy = DiskCacheStrategy.AUTOMATIC,
                        anim: Boolean = true) {
        val options = RequestOptions()
        options.run {
            diskCacheStrategy(strategy)
            override(width, height)

            when (placeholder) {
                is Int -> placeholder(placeholder)
                is Drawable -> placeholder(placeholder)
                else -> placeholder(ColorDrawable(Color.parseColor("#FFF2F2")))
            }

            when (error) {
                is Int -> error(error)
                is Drawable -> error(error)
                else -> error(ColorDrawable(Color.parseColor("#FFF2F2")))
            }

            if (anim) {
                withCrossFade()
            }
        }

        Glide.with(context).load(resouse)
                .apply(options).into(imageView)
    }

    /**
     * 加载图片bitmap
     *
     * @param context
     * @param resouse  类型为url file resId byte[] uri
     * @param callback
     */
    fun loadImageBitmap(context: Context, resouse: Any,
                        callback: OnImageLoadedListener?) {
        Glide.with(context)
                .asBitmap()
                .load(resouse)
                .listener(object : RequestListener<Bitmap> {
                    override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Bitmap>, isFirstResource: Boolean): Boolean {
                        callback?.onLoadFail()
                        return true
                    }

                    override fun onResourceReady(resource: Bitmap, model: Any, target: Target<Bitmap>, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                        callback?.onBitmapLoaded(resource)
                        return true
                    }
                })
                .preload()
    }

    /**
     * 加载图片drawable
     *
     * @param context
     * @param resouse  类型为url file resId byte[] uri
     * @param callback
     */
    fun loadImageDrawable(context: Context, resouse: Any,
                          callback: OnImageLoadedListener?) {
        Glide.with(context)
                .asDrawable()
                .load(resouse)
                .listener(object : RequestListener<Drawable> {
                    override fun onLoadFailed(e: GlideException?, model: Any, target: Target<Drawable>, isFirstResource: Boolean): Boolean {
                        callback?.onLoadFail()
                        return true
                    }

                    override fun onResourceReady(resource: Drawable, model: Any, target: Target<Drawable>, dataSource: DataSource, isFirstResource: Boolean): Boolean {
                        callback?.onDrawableLoaded(resource)
                        return true
                    }
                }).preload()
    }

    /**
     * 加载背景
     *
     * @param context
     * @param view
     * @param resouse 类型为url file resId byte[] uri
     */
    fun loadViewBackground(context: Context, view: View?, resouse: Any) {
        if (view == null) {
            return
        }

        Glide.with(context)
                .load(resouse)
                .apply(RequestOptions.fitCenterTransform())
                .into(object : SimpleTarget<Drawable>() {
                    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            view.background = resource
                        } else {
                            view.setBackgroundDrawable(resource)
                        }
                    }
                })
    }

    /**
     * 清理内存缓存的图片
     *
     * @param context
     */
    fun onLowMemory(context: Context?) {
        if (context != null) {
            Glide.get(context).clearMemory()
        }
    }

    /**
     * 清理内存
     *
     * @param context
     * @param level
     */
    fun onTrimMemory(context: Context?, level: Int) {
        if (context != null) {
            if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
                Glide.get(context).clearMemory()
            }
            Glide.get(context).trimMemory(level)
        }
    }

    fun onScrollStateChanged(context: Context, scrollState: Int) {
        if (scrollState == RecyclerView.SCROLL_STATE_IDLE) {
            resumeRequest(context)
        } else if (scrollState == RecyclerView.SCROLL_STATE_DRAGGING || scrollState == RecyclerView.SCROLL_STATE_SETTLING) {
            pauseRequest(context)
        }
    }

    /**
     * rv | lv 滚动停止时加载图片 SCROLL_STATE_IDLE
     *
     * @param context
     */
    private fun resumeRequest(context: Context?) {
        try {
            if (context != null) {
                Glide.with(context).resumeRequests()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * rv | lv 滚动时停止加载图片 SCROLL_STATE_DRAGGING SCROLL_STATE_SETTLING
     *
     * @param context
     */
    private fun pauseRequest(context: Context?) {
        try {
            if (context != null) {
                Glide.with(context).pauseRequests()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    /**
     * 清理磁盘缓存 需要在子线程中执行 建议同时clearMemory()
     */
    fun clearDiskCache() {
        Glide.get(BaseApplication.INSTANCE!!).clearDiskCache()
    }

    /**
     * 清理内存缓存  必须在UI线程中进行
     */
    fun clearMemoryCache() {
        Glide.get(BaseApplication.INSTANCE!!).clearMemory()
    }


    interface OnImageLoadedListener {

        /**
         * bitmap加载完成
         * 使用时需做非空判断
         *
         * @param bitmap
         */
        fun onBitmapLoaded(bitmap: Bitmap)

        /**
         * drawable加载完成
         * 使用时需做非空判断
         *
         * @param drawable
         */
        fun onDrawableLoaded(drawable: Drawable)

        /**
         * 图片获取失败
         */
        fun onLoadFail()
    }

}
